<?php

class FactoryPlugin{
	var $ld;
	var $xmlsOb;
	var $tableItem;
	var $tableModifier;
	
	// ==========================================================================
	function FactoryPlugin(){
		$this->ld = new LocalData();
		$this->xmlsOb = new xmlsOb();
		$this->xmlsOb->GenerateFnames();
	}
	function GetParamByName($name){
		$fl = file('options.txt');
		foreach ($fl as $line){
			if (strpos($line, $name) !== false){
				$pos = strpos($line, '=');
				$val = trim(substr($line, $pos + 1, strlen($line)));
			}
		}
		return $val;
	}
	function GetOptionsByTypeName($name){
		$res = "";
		foreach ($this->xmlsOb->gsXML->items->item as $item){
			if ((string )$item['type'] == $name){
				$res = $res . "<option>" . (string )$item['name'] . "</option>";
			}
		}
		return $res;
	}	
	function GetContract(){
		$tableName = array();
		$tableName2 = array();
		$factoryType = "premium_goods";
		$res = "";
		$ret = '<table class="table1">';
		$ret .= "<tr><td>Contract</td><td>Cost</td><td>Production time</td><td>Minimal goods</td><td>Workers needed</td><td>Maximum goods</td></tr>";

		foreach($this->xmlsOb->gsXML->items->item as $item){
			if(((string)$item['type'] == "factory_contract")  || ((string)$item['type'] == "factory_textile_contract")){
				if(isset($item->randomModifiers)){
					foreach($item->randomModifiers->modifier as $modifier){
						if($modifier['type'] == $factoryType){
							$tableName[(string)$item['name']]['table'] = $modifier['tableName'];
						}
					}
				}
				$tableName[(string)$item['name']]['workers'] = count($item->workers->worker);
				if(isset($item->goods)){
					$tableName[(string)$item['name']]['cost'] = $item->goods;
					$tableName[(string)$item['name']]['costType'] = "goods";
				}
				elseif(isset($item->cost)){
					$tableName[(string)$item['name']]['cost'] = $item->cost;
					$tableName[(string)$item['name']]['costType'] = "coins";
				}
				$tableName[(string)$item['name']]['growTime'] = $item->growTime;
			}
		}
		$this->tableItem=$tableName;
		
		foreach($this->xmlsOb->gsXML->randomModifierTables->randomModifierTable as $randomModifierTable){
			$amount = 0;
			foreach($tableName as $name=>$table){
				if((string)$randomModifierTable['name'] == (string)$table['table']){
					foreach($randomModifierTable->roll->$factoryType as $premium_goods){
						$amount +=(int)$premium_goods['amount'];
					}
					$amount = ((int)$randomModifierTable->roll['percent'] * $amount)/100;
					$Totalamount = $table['workers']* $amount + $amount;
					$cost = $table['cost'];
					$costType = $table['costType'];
					
					$growTime = (float)$table['growTime'];
					
					$tableName2[(string)$table['table']]['amount'] = (int)$amount;
					$tableName2[(string)$table['table']]['Totalamount'] = (int)$Totalamount;
					$tableName2[(string)$table['table']]['cost'] = (int)$cost;
					$tableName2[(string)$table['table']]['growTime'] = (float)$growTime;
					
					$ret .= "<tr><td>".$name."</td><td>".$cost." ".$costType."</td><td>".$this->ld->GetXMLtime($growTime)."</td><td>".$amount."</td><td>".$table['workers']."</td><td>".$Totalamount."</td></tr>";
				}
			}
		}
		$ret .= "</table>";
		$this->tableModifier=$tableName2;
		return $ret;
				
	}
	function GetFactory($worldObjects){
		$timeZone = $this->GetParamByName("sTimeZone");
		if(strlen($timeZone)<5){
			$timeZone = "Europe/Paris";
		}
		date_default_timezone_set($timeZone);

		$res = "";
		$fac = "";
		$ret = '<table class="table1">';
		$ret .= "<tr><td>Factory / ID</td><td>Contract</td><td>Started</td><td>Worker progress</td><td>Goods progress</td><td>State</td><td>Time</td></tr>";
		
		switch ($worldObjects) {
			case "main" :  $res = $this->ld->GetSelect("select * from objects"); break;
			case "downtown" :  $res = $this->ld->GetSelect("select * from dt_objects"); break;
		}
		$fac = $this->ld->GetSelect("select distinct id from Factory");
		
		foreach ($res as $val){
			$v=(string)$val[1];
			$obj=unserialize(base64_decode($v));
			if ((string)$obj['className'] == "Factory" ){
				
				$id = $obj['id'];
				$itemName = $obj['itemName'];
				$contractName = $obj['contractName'];
				$plantTime = $obj['plantTime'];
				
				$state = $obj['state'];
				if(isset($contractName)){
					foreach((array)$fac as $info){
						if($id == $info["id"]){
							$facCount = $this->ld->GetSelect("select count(*) as Number from Factory where id ='$id' and Number != '-'");
							$filled = $facCount[0]["Number"];
							foreach($this->tableItem as $name=>$table){
								if((string)$contractName == (string)$name){
									foreach($this->tableModifier as $name2=>$table2){
										if((string)$table['table'] == (string)$name2){
											
											$goods = $table2['amount'] + $table2['amount'] * $filled;
											if($filled==$table['workers']) $moreText = " (FULL)"; else $moreText ="";
											if($goods == $table2['Totalamount']) $moreText2 = " (MAX)";	else $moreText2 = "";
											$timeReady = $plantTime/1000 + $table2['growTime']*23*60*60;
											$plantTime = $this->ld->nicetime($plantTime/1000);
											
											if ($state == "planted"){
												$state = "working";
												$timeReady = ' ready in '.$this->ld->nicetime($timeReady)." (".date('H:i:s d M Y', $timeReady).")";
											}
											elseif ($state == "grown") {
												$state = "ready to collect";
												$timeReady = ' finished '.$this->ld->nicetime($timeReady)." (".date('H:i:s d M Y', $timeReady).")";
											}
											$contractNum = substr($contractName, -1);
											
											$ret .= "<tr><td>".$itemName." / ".$id."</td><td title=$contractName>".$contractNum."</td><td>".$plantTime."</td><td>".$filled."/".$table['workers'].$moreText."</td><td>".$goods."/".$table2['Totalamount'].$moreText2."</td><td>".$state."</td><td>".$timeReady."</td></tr>";
										}
									}
								}
							}
						}
					}
				}
				else{
					if($state == "plowed"){ 
						$state = "not working";
					}

					$ret .= "<tr><td>".$itemName." / ".$id."</td><td>-</td><td>-</td><td>-</td><td>-</td><td>".$state."</td><td>-</td></tr>";
				}
				
			}
		}
		$ret .= "</table>";
		return $ret;
	}
	function SelectFactoryMainWorld(){
		$Factory = (array )$this->ld->GetPlSettings('Factory');
		if(!isset($Factory['collectFactoryIN'])) $Factory['collectFactoryIN'] = array();
		$facNOT="";
		$facN = array();
		$facIN="";
		$facI = array();
		$objects = $this->ld->GetObjects();
		foreach ($objects as $key=>$item){
			if ((string)$item['className'] == "Factory"){
				$found = "N";
				if (in_array((string)$item['id'],$Factory['collectFactoryIN'])){
					$found = "Y";
				}
				if($found == "Y"){ 
					$facI[$item['id']] = (string)$item['itemName'];
				}
				else{ 
					$facN[$item['id']] = (string)$item['itemName'];
				}
			}
		}
		natcasesort($facI);
		natcasesort($facN);
		foreach ($facI as $id=>$item){
			$facIN .= '<option value="'.$id.'">'.$item." (".$id.")</option>";
		}
		foreach ($facN as $id=>$item){
			$facNOT .= '<option value="'.$id.'">'.$item." (".$id.")</option>";
		}
		echo '
		<table class="table0">
			<tr><th>DO NOT Harvest/Place contract </th><th></th><th> Do Harvest/Place contract </th></tr>
			<tr>
				<td><select name="sell7" size="5" multiple="multiple" title="DO NOT Harvest/Place contract">'.$facNOT.'</select></td>
				<td align="center" valign="middle">
					<input type="button" value="--&gt;"onclick="moveOptions(this.form.sell7, this.form.sell8); sortSelect(this.form.sell8)" /><br />
					<input type="button" value="&lt;--"onclick="moveOptions(this.form.sell8, this.form.sell7); sortSelect(this.form.sell7)" />
				</td>
				<td><select name="sell8" size="5" multiple="multiple" id="collectFactoryIN" title="DO Harvest/Place contract">'.$facIN.'</select></td>
			</tr>
		</table>';
	}
	function SelectFactoryDowntown(){
		$Factory = (array )$this->ld->GetPlSettings('Factory');
		if(!isset($Factory['collectFactoryINDt'])) $Factory['collectFactoryINDt'] = array();
		$facNOT="";
		$facN = array();
		$facIN="";
		$facI = array();
		$objects = $this->ld->GetDTObjects();
		foreach ($objects as $key=>$item){
			if ((string)$item['className'] == "Factory"){
				$found = "N";
				if (in_array((string)$item['id'],$Factory['collectFactoryINDt'])){
					$found = "Y";
				}
				if($found == "Y"){ 
					$facI[$item['id']] = (string)$item['itemName'];
				}
				else{ 
					$facN[$item['id']] = (string)$item['itemName'];
				}
			}
		}
		natcasesort($facI);
		natcasesort($facN);
		foreach ($facI as $id=>$item){
			$facIN .= '<option value="'.$id.'">'.$item." (".$id.")</option>";
		}
		foreach ($facN as $id=>$item){
			$facNOT .= '<option value="'.$id.'">'.$item." (".$id.")</option>";
		}
		echo '
		<table class="table0">
			<tr><th>DO NOT Harvest/Place contract </th><th></th><th> Do Harvest/Place contract </th></tr>
			<tr>
				<td><select name="sell71" size="5" multiple="multiple" title="DO NOT Harvest/Place contract">'.$facNOT.'</select></td>
				<td align="center" valign="middle">
					<input type="button" value="--&gt;"onclick="moveOptions(this.form.sell71, this.form.sell81); sortSelect(this.form.sell81)" /><br />
					<input type="button" value="&lt;--"onclick="moveOptions(this.form.sell81, this.form.sell71); sortSelect(this.form.sell71)" />
				</td>
				<td><select name="sell81" size="5" multiple="multiple" id="collectFactoryINDt" title="DO Harvest/Place contract">'.$facIN.'</select></td>
			</tr>
		</table>';
	}
	// ==========================================================================
	function GetForm(){

		
		$vername='Factory';
		$verauth='Anhoc';
		
		if(file_exists('Plugins\Factory\description.txt')){
			$verdesc=file('Plugins\Factory\description.txt');
		}
		foreach ($verdesc as $dsc) {
			$dkey='';$dval='';
			list($dkey,$dval)=explode("=",$dsc);
			if (isset($dkey))
			if ($dkey=="name") $vername=trim($dval);
			if ($dkey=="version") $version=trim($dval);
			if ($dkey=="date") $verdate=trim($dval);
			if ($dkey=="author") $verauth=trim($dval);
			if ($dkey=="descr") $verdesc=trim($dval);
		}
		echo '
		<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
		<html xmlns="http://www.w3.org/1999/xhtml" lang="ru">
			<head>
				<title>Factory</title>
				<script src="..\..\codebase-php\jquery-1.4.2.min.js"></script>
				<script src="..\..\codebase-php\jquery.json-2.2.min.js"></script>
				<script type="text/javascript" src="helpers/validation.js"></script>
				<link href="helpers/plugin.css" rel="stylesheet" type="text/css">
				<script>
					window.reload = function(){
						var l=window.location.toString();
						var indx=l.indexOf(\'?\');
						window.location=l.slice(0, indx)+"?action=refresh&tmp="+Math.random();
					}
				
					$(document).ready(function(){                                                                                  
						window.settings=eval('.json_encode($this->ld->GetPlSettings('Factory')).');

						if ((window.settings!==null) && (window.settings!==undefined)){
							$("#factorylist").val(window.settings.factorylist);
							$("#factorylist2").val(window.settings.factorylist2);

							$(":checkbox").each(
								function(){
								if(window.settings[$(this).attr("id")]==true){
									$(this).attr("checked", true);
								}
								else{
									$(this).attr("checked", false);
								}
							});
							$(":radio").each(
								function(){
								if(window.settings[$(this).attr("id")]==true){
									$(this).attr("checked", true);
								}
								else{
									$(this).attr("checked", false);
								}
							});
							$(":text").each(
								function (){
								var attr=$(this).attr("id");
								if (window.settings[attr]!==null){
									$(this).val(window.settings[attr]);
								}
								else{
									$(this).val("0");
								}
							});
						}
						//==============================================================

						$("#btn_save").click(function(){
							var req=new Object();
							
							$(":checkbox").each(function(){
								var par=$(this).attr("id");
								req[par]=$(this).attr("checked");
								if (($(this).attr("objid")!==null) && ($(this).attr("objid")!==undefined))
								{
								req[par+"ID"]=$(this).attr("objid");
								}
							});
							
							$(":radio").each(function(){
								var par=$(this).attr("id");
								req[par]=$(this).attr("checked");
								if (($(this).attr("objid")!==null) && ($(this).attr("objid")!==undefined))
								{
								req[par+"ID"]=$(this).attr("objid");
								}
							});
							
							$("input:text").each(function(){
							req[$(this).attr("id")]=$(this).val();
							});
							
							req["factorylist"]=$("#factorylist").val();
							req["factorylist2"]=$("#factorylist2").val();
													
							req.collectFactoryIN=new Array();
							$("#collectFactoryIN option").each(function(){
								var par=$(this).val();
								req.collectFactoryIN.push(par);
							});
							req.collectFactoryINDt=new Array();
							$("#collectFactoryINDt option").each(function(){
								var par=$(this).val();
								req.collectFactoryINDt.push(par);
							});
							
							data=$.toJSON(req);
							var l=window.location.toString();
							var indx=l.indexOf(\'?\');
							var nurl=l.slice(0, indx)+"?action=save&tmp="+Math.random();
							$.post(nurl, data);

							return false;
						});
					});
					
					//==============================================================
					function sortSelect(selElem) {
						var tmpAry = new Array();
						for (var i=0;i<selElem.options.length;i++) {
								tmpAry[i] = new Array();
								tmpAry[i][0] = selElem.options[i].text;
								tmpAry[i][1] = selElem.options[i].value;
						}
						tmpAry.sort();
						while (selElem.options.length > 0) {
							selElem.options[0] = null;
						}
						for (var i=0;i<tmpAry.length;i++) {
								var op = new Option(tmpAry[i][0], tmpAry[i][1]);
								selElem.options[i] = op;
						}
						return;
					}
						
				
					var NS4 = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) < 5);
					function addOption(theSel, theText, theValue){
						var newOpt = new Option(theText, theValue);
						var selLength = theSel.length;
						theSel.options[selLength] = newOpt;
					}

					function deleteOption(theSel, theIndex){
						var selLength = theSel.length;
						if(selLength>0)
						{
						theSel.options[theIndex] = null;
						}
					}

					function moveOptions(theSelFrom, theSelTo){
						var selLength = theSelFrom.length;
						var selectedText = new Array();
						var selectedValues = new Array();
						var selectedCount = 0;
						var i;
						// Find the selected Options in reverse order and delete them from the from Select.
						for(i=selLength-1; i>=0; i--){
							if(theSelFrom.options[i].selected){
								selectedText[selectedCount] = theSelFrom.options[i].text;
								selectedValues[selectedCount] = theSelFrom.options[i].value;
								deleteOption(theSelFrom, i);
								selectedCount++;
							}
						}

						// Add the selected text/values in reverse order.
						// This will add the Options to the TO Select
						// in the same order as they were in the FROM Select.
						for(i=selectedCount-1; i>=0; i--){
							addOption(theSelTo, selectedText[i], selectedValues[i]);
						}

						if(NS4) history.go(0);
					}
				</script>    
			</head>
			<body>
			<form>
				<table border="1" cellspacing="1" cellpadding="1" width="100%" bgcolor="#E357FF">
					<tr height="23">
						<td><hr><h1>'.$vername.' v'.$version.'</h1>
						<h3> - Original by Phreaker, rewrite by '.$verauth.'</h3>
						<hr></td>
					</tr>
				</table>
				<div class="clear"></div><br>
				
				<!--
				Run the plugin
				-->
				<div id="content_main" class="grid">
					<fieldset class="ui-fieldset">
					<legend>Start plugin</legend>
					<input type="checkbox" id="run" title="Check if you want to start the plugin :)"/> Run Factory plugin?<br><br>
				</div>
				
				
				<!--
				Choose the option
				-->
				<div id="content_main" class="grid">
					<fieldset class="ui-fieldset">
					<legend>Option</legend>
					<input id="NoHarvestIfFull" type="checkbox" title="Check if you want to stop if premium goods are more than 90%"> Stop Harvest if premium goods total is 90% full ?<br>
					<input type="checkbox" id="Fbonus" title="Check if you want to have coins bonus when harvesting !"> Streak Bonus<br>
				</fieldset><br>
				</div><br>	
					
					
				<!--
				Choose the contract
				-->
				<div id="content_main" class="grid">
					<fieldset class="ui-fieldset">
					<legend>Contract</legend>
					<b> &nbsp;&nbsp;- On standard factory</b>, place contract:&nbsp;<select id="factorylist" title="See Information section below for more details">'.$this->GetOptionsByTypeName("factory_contract").'</select><br>
					<b> &nbsp;&nbsp;- On textile factory</b>, place contract:&nbsp;<select id="factorylist2" title="See Information section below for more details">'.$this->GetOptionsByTypeName("factory_textile_contract").'</select><br>
					</fieldset><br>
				</div>
				
				
				<!--
				Choose Main World factory 
				-->
				<div id="content_main" class="grid">
					<fieldset class="ui-fieldset">
					<legend>Main World Factory</legend>
						<input id="harvestsfactory" type="checkbox" title="Do you want to harvest the factory?"> Harvest factory ?<br>
						<input type="checkbox" id="placeContract" title="Do you want to start a work in factory? Choose also the contract"> Place Contract ?<br>';
						$this->SelectFactoryMainWorld();echo '<br>
					</fieldset>
				</div>

				<!--
				Choose Downtown factory 
				-->
				<div id="content_main" class="grid">
					<fieldset class="ui-fieldset">
					<legend>Downtown Factory</legend>
						<input id="harvestsfactory2" type="checkbox" title="Do you want to harvest the factory?"> Harvest factory ?<br>
						<input type="checkbox" id="placeContract2" title="Do you want to start a work in factory? Choose also the contract"> Place Contract ?<br>';
						$this->SelectFactoryDowntown();echo '<br>
					</fieldset>
				</div>

				
				<!--
				Save
				-->
				<div width="100%" align="center"><hr>
				<button id="btn_save" style="color:white;background-color:#13a89e;border-width:1px;border-style:solid; " title="Click to save your settings">&nbsp; Save settings&nbsp;</button>
				<hr></div>
				<br>
				
				
				<!--
				Information
				-->
				<div id="content_main" class="grid">
					<fieldset class="ui-fieldset">
					<legend>Information Contracts</legend>
						&nbsp;&nbsp;- Main & Downtown World -<br>
						&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>'.$this->GetContract().'<br>
					</fieldset>
				</div>
                <br>
				<div id="content_main" class="grid">
					<fieldset class="ui-fieldset">
					<legend>Information Factories</legend>
						&nbsp;&nbsp;- Main World -<br>
						&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Main world Factory.<br>'.$this->GetFactory("main").'<hr>
						&nbsp;&nbsp;- Downtown World -<br>
						&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Downtown Factory.<br>'.$this->GetFactory("downtown").'
					</fieldset>
				</div>
				
			</form>
			</body>
		</html>';
	}
}

?>
